

//Variables
var project_uid = '{{ project_uid }}';
var username = '{{ user.username }}';
var editor_tb;
var treepanel;
var viewport;
var tbar;
var main_panel;
var isCtrl = false;
var isCmd = false;
var tabs = {count: 0, isCmd: false, isCtrl: false};
var messages = new Array();

//#################################################//

//Loading JQUERY
$(document).ready(function(){
    init_log();
    
    console.log('jquery init');

});

//#################################################//

Ext.onReady(function(){

    console.log('Ext.onReady');
    Ext.QuickTips.init();
    create_tree_panel();
    create_main_panel();
    //setting provider
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    create_layout();
    //create_editor_toolbar();

    var iframe = document.getElementById("editor12");
    

});

//#################################################//

function init_log(){
	if (window['loadFirebugConsole']) {
	   window.loadFirebugConsole();
	} else {
	   if (!window['console']) {
	       window.console = {};
	       f = function func(arg){};
	       window.console.info = f;
	       window.console.log = f;
	       window.console.warn = f;
	       window.console.error = f;
	   }
	}
}

//#################################################//

function create_tree_panel(){
    tree_panel = new Ext.tree.TreePanel({
	    useArrows: true,
	    autoScroll: true,
	    animate: true,
	    enableDD: true,
	    containerScroll: true,
	    border: true,
	    width: 175,
	    height: '100%',
	    // auto create TreeLoader
	    dataUrl: '/{{ project_name }}/tree/get/',
	    //rootVisible: false,
	    listeners: {
	        click: function(n) {
	            //Temporary fix
	            
	            if (n.attributes.type == 'project_status'){
	            
	            }
	            
	            if (n.attributes.type == 'page'){
	            
	               //If select page not exists:
	               if (! eval('tabs.page_'+ n.attributes.id)){
	                   console.log('Open new page [' + tabs.count + ']');
	                   tab_open_page(n);
	               }else{
	                   console.log('Activate Tab [' + tabs.count + ']');
	                   main_panel.activate('page_' + n.attributes.id)
	               }
	            }
	        }
	    },
	    
	    root: {
	        nodeType: 'async',
	        text: '{{ project_name }}',
	        draggable: false,
	        id: '',
	        expanded: true,
	        expandable: false,
	        listeners: {
	           beforecollapse: function(n){return false},
	           click: function(n){return false},
	        }
	    }
    }); 
}

//#################################################//

function tab_open_page(n){
    $.getJSON("/{{project_uid}}/p/" + n.attributes.id + "/t/draft/get_content/",
	    function(data){
	        main_panel.add({
	            title: n.attributes.text,
	            id: 'page_' + n.attributes.id,
	            iconCls: 'tabs',
	            autoScroll: 'false',
	            style: {overflow: 'hidden'},
	            height: 500,
	            closable:true,
	            layout:'border',
	            tbar: make_editor_toolbar(n.attributes.id, data.tag_uid),
	            bbar:  new Ext.ux.StatusBar( {
                    id: 'statusbar_' + n.attributes.id,
		            text: 'Ready',
		            iconCls: 'x-status-valid',
                }),
	            items: [

                {
                    collapsible: false,
                    region:'center',
                    margins: '0 0 0 0',
                    autoScroll: 'false',
                    cls: 'papercontainer',
                    html: '<div id="paper_' + n.attributes.id + '" class="paper">' + data.content + '</div>',
                }],
                listeners: {
                    close: function(p){
                        eval('delete tabs.page_' + n.attributes.id);
                        tabs.count = tabs.count-1;
                        console.log('closing page ' + n.attributes.id + ' [' + tabs.count + 'remainings]');
                    },
                }
            }).show().setAutoScroll(false);
            
            Ext.fly('paper_' + n.attributes.id).on('keypress', function(){
		        var sb = Ext.getCmp('statusbar_' + n.attributes.id);
		        sb.showBusy('Saving draft...');
		        save_page(n.attributes.id, data.tag_uid);

		    }, this, {buffer:5000});

	        var editor_id = 'paper_' + n.attributes.id;
		    document.getElementById(editor_id).designMode = "on";
		    document.getElementById(editor_id).contentEditable = true; 
		    //document.getElementById(editor_id).focus();
		    console.log('Editing mode on for page_' + n.attributes.id);
		    var item = {id: n.attributes.id, tag_uid: data.tag_uid, keys: {isCtrl: false, isCmd: false }}; 
		    eval('tabs.page_' + n.attributes.id + ' = item;');
		    
		    //Configure shortcut
		    config_keyboard_shortcuts(n.attributes.id, data.tag_uid);
		    
		    //Retrieve comment for page
		    var comments = new Array();
	        $('.comment').each(function(i, o){
		        console.log('in comment: ' + o.id);
		        var comment_uid = o.id;
		        comment_uid = comment_uid.replace('comment_', '');
		        comments[i] = comment_uid;
		    });
		    $('#' + editor_id).data('comments', comments);
		    console.log('comments: ' + comments);
		    
        }
    );
    
    eval('tabs.page_' + n.attributes.id + ' = null;');
    tabs.count = tabs.count+1;
}

//#################################################//

function make_editor_toolbar(page_uid, tag_uid){

    var editor_id = 'paper_' + page_uid;
    return [
        {iconCls: 'save_button', tooltip: {text:'Save Document', title: 'CTRL+S'}, handler: function(item){save_page(page_uid, tag_uid);},},
        '-',
        {iconCls: 'bold_button', id:'bold', enableToggle: false, tooltip: {text:'Apply Bold to selection', title: 'CTRL+B'},
            handler: function(item){
                console.log('in bold: ' + editor_id);
                document.execCommand('bold', false, null);
            },
        },
        {iconCls: 'italic_button', enableToggle: false, tooltip: {text:'Apply Italic to selection', title: 'CTRL+I'},
            handler: function(item){
                document.execCommand('italic', false, null);
            },
        },
        {iconCls: 'underline_button', enableToggle: false, tooltip: {text:'Underline the selection', title: 'CTRL+U'},
            handler: function(item){
                document.execCommand('underline', false, null);
            },
        },
        {iconCls: 'strikethrough_button', enableToggle: false, tooltip: {text:'Strikethrough the selection', title: 'CTRL+P'},
            handler: function(item){
                document.execCommand('strikethrough', false, null);
            },
        },
        '-',
        {iconCls: 'align_left_button', enableToggle: false, tooltip: {text:'Align Left', title: 'CTRL+A+L'},
            handler: function(item){
                document.execCommand('justifyleft', false, null);
            },
        },
        {iconCls: 'align_center_button', enableToggle: false, tooltip: {text:'Align Center', title: 'CTRL+A+C'},
            handler: function(item){
                document.execCommand('justifycenter', false, null);
            },
        },
        {iconCls: 'align_right_button', enableToggle: false, tooltip: {text:'Align Right', title: 'CTRL+A+R'},
            handler: function(item){
                document.execCommand('justifyright', false, null);
            },
        },
        {iconCls: 'align_justify_button', enableToggle: false, tooltip: {text:'Justify Text', title: 'CTRL+A+J'},
            handler: function(item){
                document.execCommand('justifyfull', false, null);
            },
        },
        '-',
        {iconCls: 'decrease_indent_button', enableToggle: false, tooltip: {text:'Decrease Indent', title: 'CTRL+I+D'},
            handler: function(item){
                document.execCommand('outdent', false, null);
            },
        },
        {iconCls: 'increase_indent_button', enableToggle: false, tooltip: {text:'Increase Indent', title: 'CTRL+I+I'},
            handler: function(item){
                document.execCommand('indent', false, null);
            },
        },
        '-',
        {iconCls: 'unordered_list_button', enableToggle: false, tooltip: {text:'Insert Bullet List', title: 'CTRL+L+B'},
            handler: function(item){
                console.log('in unordered list');
                document.execCommand('insertunorderedlist', false, null);
            },
        },
        {iconCls: 'ordered_list_button', enableToggle: false, tooltip: {text:'Insert Numeric List', title: 'CTRL+L+N'},
            handler: function(item){
                var a = document.execCommand('insertorderedlist', false, null);
                console.log(a);
            },
        },
        '-',
        {iconCls: 'horizontal_line_button', enableToggle: false, tooltip: {text:'Insert Horizontal Line', title: 'CTRL+H'},
            handler: function(item){
                document.execCommand('inserthorizontalrule', false, null);
            },
        },
        '-',
        {iconCls: 'comment_button', enableToggle: false, tooltip: {text:'Insert Comment', title: 'CTRL+M'},
            handler: function(item){
                insert_comment(page_uid, tag_uid);
            },
        }, //html_delete.png
        {iconCls: 'remove_formatting_button', enableToggle: false, tooltip: {text:'Remove Formatting', title: ''},
            handler: function(item){
                remove_formatting(page_uid, tag_uid);
            },
        },
        '-',
    ]
}

//#################################################//

function create_layout(){
    viewport = new Ext.Viewport({
        layout:'border',
        renderTo: document.getElementById('centraldiv'),
        defaults : {
            frame : true, 
            split : true,
        },
        items:[

            {
            region:'west',
            id:'west-panel',
            title:'Project Navigation',
            xtype: 'panel',
            split:true,
            width: 188,
            minSize: 188,
            maxSize: 400,
            collapsible: true,
            margins:'35 0 5 5',
            cmargins:'35 5 5 5',
            layout:'column',
            layoutConfig:{
                animate:true
            },
            items: [
                tree_panel
            ]
        },{
            region:'center',
            margins:'35 5 5 0',
            layout: 'fit',
            //xtype: 'panel',
            autoScroll:false,
            border: true,
            items: 
                [main_panel]

            
        }]
    });
}

//#################################################//

function create_main_panel(){

    console.log('in main panel');
    main_panel = new Ext.TabPanel({
        width:'100%',
        activeTab: 0,
        autoScroll: false,
        enableTabScroll:true,
        items:[
	        {
	               title: 'Project Status',
                   //closable:true,
            }
	    ]    
    });
    
    //Enable content editable

    
    console.log('end of main panel');
}

//#################################################//

var _var_project_name;
var _var_text;


//#################################################//

function config_keyboard_shortcuts(page_uid, tag_uid){
    
    //retrieve tab obj
    //var current_tab = eval('tabs.page_' + page_uid);
    
    
    console.log('in config keyboard');

    $('#paper_'+page_uid).keydown(function (e) {
    
        
        if(e.which == 66 && (e.metaKey || e.ctrlKey)) {
            console.log('CTRL+B pressed');
            document.execCommand('bold', false, null);
            return false;
        }
        
        if(e.which == 73 && (e.metaKey || e.ctrlKey)) {
            console.log('CTRL+I pressed');
            document.execCommand('italic', false, null);
            return false;
        }        
        
        if(e.which == 83 && (e.metaKey || e.ctrlKey)) {
            console.log('saved');
            save_page(page_uid, tag_uid);
            return false;
        }
    });
}

//#################################################//

function save_page(page_uid, tag_uid){
    var text = $('#paper_' + page_uid).html();
    console.log('In new save page Text: ' + text);
    
    console.log('saving comments');
    //Salviamo i commenti
    var comments = $('#paper_' + page_uid).data('comments');
    console.log(comments);
    var comments_to_remove = new Array();
    $.each(comments, function(index, value) { 
        //Controllo se esiste ancora il commento
        console.log('previous comment: ' + value);
        if ($('#comment_' + value).length == 0){
            console.log('comment to remove: ' + value);
            comments_to_remove[comments_to_remove.length] = value;
        }else{
            console.log('comment to save: ' + value);
        }
    });
    console.log('comments to remove: ' + comments_to_remove);

    $.each(comments_to_remove, function(i, o){
        console.log('removing comment: ' + o);
        $.post("/{{ project_uid }}/messages/remove/" + o + "/", {}, 
            function(data){
            if (data.message == 'DONE'){
                console.log('DONE');
            }else if (data.message == 'NOTHING'){
                console.log('NOTHING');
                
            }else{
                console.log('ERROR SAVING');
                
            }
        },
        "json");

    });
    var new_comments = new Array();    
    $('.comment').each(function(i, o){
        var comment_uid = o.id;
        comment_uid = comment_uid.replace('comment_', '');
        new_comments[i] = comment_uid; //update comments references
        console.log('saving comment: ' + comment_uid);
        var comment_date = $( '#comment_date_' + comment_uid ).html();
        var comment_text = $( '#comment_text_' + comment_uid ).html();
        $.post("/{{ project_uid }}/messages/save/" + comment_uid + "/", 
                {
                    date :      comment_date,
                    text :      comment_text,
                    document_uid :  page_uid,
                    document_type : 'page',
                    message_type : 0,
                }, 
            function(data){
            if (data.message == 'DONE'){
                console.log('DONE');
            }else if (data.message == 'NOTHING'){
                console.log('NOTHING');
                
            }else{
                console.log('ERROR SAVING');
                
            }
        },
        "json");        

    });
    $('#paper_' + page_uid).data('comments', new_comments);
    
    
    
    $.post("/pages/save/" + tag_uid + "/", {
        'text': text,
        },
        function(data){
            //alert(data.message); // John
            console.log(data.message);
            var sb = Ext.getCmp('statusbar_' + page_uid);
                
            if (data.message == 'DONE'){
                console.log('DONE');
                //Ext.example.msg('','Page Saved');
                sb.setStatus({
                    iconCls: 'x-status-valid',
                    text: 'Draft auto-saved at ' + new Date().format('g:i:s A')
                });
            }else if (data.message == 'NOTHING'){
                sb.setStatus({
                    iconCls: 'x-status-valid',
                    text: 'Nothing to save.'
                });
            }else{
                sb.setStatus({
                    iconCls: 'x-status-error',
                    text: 'Error Saving Draft. Do it manually.'
                });
            }

            
    }, "json");
}


//#################################################//

function insert_comment(page_uid, tag_uid){

    var userSelection;
    if (window.getSelection) {
        userSelection = window.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        userSelection = document.selection.createRange();
    }
    console.log('UserSelection: ' + userSelection);
    
    var selectedText = userSelection;
    if (userSelection.text)
        selectedText = userSelection.text;
    
    
    var rangeObject = getRangeObject(userSelection);

    function getRangeObject(selectionObject) {
 //       if (selectionObject.getRangeAt)
 //           return selectionObject.getRangeAt(0);

        if (selectionObject.getRangeAt){
            console.log('getRangeAt');
            var range = selectionObject.getRangeAt(0);
            return range;
            //var final_range = document.createRange();
//            final_range.setStartBefore(range1.startContainer);
//            final_range.setEndAfter(range1.endContainer);
//            //return selectionObject.getRangeAt(0);
//            return final_range;
            
        }else { // Safari!
            var range = document.createRange();
            range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
            range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
            return range;
        }
    }
    
//    console.log( $(rangeObject.startContainer).parents().index( $('#paper_' + page_uid)) >= 0 );
//    console.log( $(rangeObject.endContainer ).parents().index( $('#paper_' + page_uid)) >= 0 );
//    console.log( 'commonAncestor: ' + $(rangeObject.commonAncestorContainer).attr('id'));
//    console.log( 'page_uid: ' + page_uid)
//    console.log( 'paper: ' + $('#paper_' + page_uid).attr('id'));
//    console.log( $( rangeObject.commonAncestorContainer).parents().index( $('#paper_' + page_uid) ) >= 0);
    
    //Check if common ancestor of range is the current paper
    if ( $( rangeObject.commonAncestorContainer )[0] == $('#paper_' + page_uid)[0] || 
         $( rangeObject.commonAncestorContainer ).parents().index( $('#paper_' + page_uid) ) >= 0
    ){
    
        console.log('in usr');

        var comment_id = SHA1(Math.random().toString());

        var user_txt = document.createTextNode(' - [' + username + '] ');
        var date_txt = document.createTextNode(getCurrentDateToString());
        
        var div_date = document.createElement('div');
        div_date.setAttribute('id', 'comment_date_' + comment_id);
        div_date.setAttribute('class', 'comment_date');
        div_date.appendChild(date_txt);
        
        var div_user = document.createElement('div'); 
        div_user.setAttribute('id', 'comment_user_' + comment_id);
        div_user.setAttribute('class', 'comment_user');
        div_user.appendChild(user_txt);

        var div_text = document.createElement('div'); 
        div_text.setAttribute('id', 'comment_text_' + comment_id);
        div_text.setAttribute('class', 'comment_text');
        div_text.appendChild(rangeObject.extractContents());

        var comment_div = document.createElement('div'); 
        comment_div.setAttribute('id', 'comment_' + comment_id)
        comment_div.setAttribute('class', 'comment');
        comment_div.appendChild(div_text); 
        comment_div.appendChild(div_user); 
        comment_div.appendChild(div_date); 
        
        rangeObject.insertNode(comment_div);
    }
//        var comment_span = document.createElement('span');
//        comment_span.setAttribute('class', 'comment');
//        comment_span.setAttribute('id', 'comment_' + comment_id)

//        comment_span.appendChild(rangeObject.extractContents());
//        comment_span.appendChild(div2);
        
        //console.log('in div: ' + div.innerHTML);    
        
        
        //Inserisco il commento nella lista dei commenti.
        var comments = $('#paper_' + page_uid).data('comments');
        comments[comments.length] = comment_id;
        $('#paper_' + page_uid).data('comments', comments);
        //#################

        var div2 = document.createElement('div'); 
        div2.appendChild(rangeObject.cloneContents()); 
        //console.log('in div2: ' + comment_span.innerHTML);           

        
        $('#comment_' + comment_id).mouseenter(function() {
            console.log('in comment' + comment_id);
        });
        $('#comment_' + comment_id).rightClick(function(data) {
            console.log('clicked' + data);
            //console.log(inspect(data));
            var contextMenu = getCommentContextMenu(page_uid);
			
			var xy = [data.clientX, data.clientY];
			console.log(data.clientX);
            console.log(data.clientY);
   			console.log(xy);
   			contextMenu.showAt(xy);
        });
}

//#################################################//

function getCurrentDateToString(){

    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    if (month < 10){
      month = "0" + month
    }       
    var day = currentTime.getDate();
    if (day < 10){
      day = "0" + day
    }  
    var year = currentTime.getFullYear();
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var APM;
    if (minutes < 10){
      minutes = "0" + minutes
    }
    if(hours > 11){
        APM = 'PM';
    } else {
        APM = 'AM';
    }
    return day + '-' + month + '-' + year + ' ' + hours + ':' + minutes + ' ' + APM
}

//#################################################//


function getCommentContextMenu(page_uid){
    return new Ext.menu.Menu({
        items: [{
        text: 'Remove Comment'
        },]
    }); 
            

}

//#################################################//

function remove_formatting(page_uid, tag_uid){
    console.log('Remove formatting')
    
    var userSelection;
    if (window.getSelection) {
        console.log('windowselection');
        userSelection = window.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        userSelection = document.selection.createRange();
        console.log('create range from selection');
    }
    //console.log('UserSelection: ' + userSelection.anchorNode.getAttribute('id'));
    
    var selectedText = userSelection;
    if (userSelection.text)
        selectedText = userSelection.text;
    
    
    var rangeObject = getRangeObject(userSelection);

    function getRangeObject(selectionObject) {
        if (selectionObject.getRangeAt){
            console.log('getRangeAt');
            return selectionObject.getRangeAt(0);
//            var final_range = document.createRange();
//            final_range.setStartBefore(range1.startContainer);
//            final_range.setEndAfter(range1.endContainer);
//            //return selectionObject.getRangeAt(0);
//            return final_range;

        } else { // Safari!
            var range = document.createRange();
            console.log('create range from scratch');
            range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
            range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
            return range;
        }
    }
    //if ($(userSelection.anchorNode).parents().is('#paper_' + page_uid) && $(userSelection.focusNode).parents().is('#paper_' + page_uid)){
    var txt = document.createTextNode(userSelection);
    rangeObject.deleteContents();
    rangeObject.insertNode(txt);
    
    //}
}

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}


function disableSelection(target){

if (typeof target.onselectstart!="undefined") //IE route

    target.onselectstart=function(){return false}

else if (typeof target.style.MozUserSelect!="undefined") //Firefox route

    target.style.MozUserSelect="none"

else //All other route (ie: Opera)

    target.onmousedown=function(){return false}
    target.style.cursor = "default"

}